import { defineStore } from 'pinia'
import request from '../../utils/request'

const mainStore = defineStore('main',{
  state:() => {
    return{
      list: [] as {id:number;name:string;done:boolean}[],
    }
  },
  actions:{
    /**
     * 获取数据
     */
    async getTodos(){
      const res = await request.get('/')
      const data = res.data as {id:number;name:string;done:boolean}[]
      console.log('res.data:' + res.data)
      this.list = data
      console.log(this.list)  
    },
    /**
     * 根据id删除数据
     * @param id 数据id
     */
    async delTodo(id:number){
      await request.delete(`${id}`)
      this.getTodos() 
    },
    /**
     * 更新数据
     * @param id 根据id修改数据
     * @param key 更新谁
     * @param value 更新为什么
     */
    async updateTodo(id:number,key:string,value:boolean|string) {
      await request.patch(`/${id}`,{
        [key]:value
      })
      this.getTodos()      
    },
    /**
     * 添加操作
     * @param name 添加数据
     */
    async addTodo(name:string){
      await request.post('/',{
        name,
        done:false,
      })
      this.getTodos()
    },
    /**
     * 更新状态
     * @param done 状态改变
     */
    async updateAllStatus(done:boolean){
      const arrPromise = this.list.map((item)=>{
        return this.updateTodo(item.id,'done',done)
      })
      await Promise.all(arrPromise)
      this.getTodos()
    },
    /**
     * 清空已完成
     */
    async clearCompleted(){
      const arrPromise = this.computed.map((item) =>{
        return request.delete(`/${item.id}`)
      })
      await Promise.all(arrPromise)
      this.getTodos()
    }

  },
  getters:{
    mainRadioStaus(state){
      return state.list.every((item)=>{
        item.done
      })
    },
    /**
     * 已完成的数据
     */
    computed(state){
      return state.list.filter((item)=> item.done)
    },
    /**
     * 未完成的数据
     */
    unCompleted(state){
      return state.list.filter((item)=> !item.done)
    }
  }
})

export default mainStore